package com.mo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.mo.common.domain.AjaxResult;
import com.mo.common.util.EasyExcelUtil;
import com.mo.domain.User;
import com.mo.service.impl.ExportServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author msy
 * @date 2022/3/28
 */
@RequestMapping("/excel")
@Controller
public class ExportController {

    @Autowired
    private ExportServiceImp service;

    /**
     * 用户信息导出
     */
    @GetMapping("export")
    @ResponseBody
    public void export(HttpServletResponse response) {
        List<User> list = service.export();
/*      方式一     下载固定位置
        EasyExcelUtil.exportExcel(list,"人员名单",User.class);
*/
//方式二       指定存储位置
        try {
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            //防止乱码
            String fileName = URLEncoder.encode("人员名单", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), User.class)
                    .sheet().doWrite(service.export());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转
     */
    @GetMapping("importExcel")
    public String importExcel() {
        return "/importExcel";
    }

    /**
     * 用户信息批量导入
     */
    @PostMapping("importExcel")
    @ResponseBody
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        int result = service.importExcel(file);
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}
